package com.nbicc.dp.wsgateway.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nbicc.core.utils.ExceptionUtil;
import com.nbicc.dp.modular.exception.custom.CustomException;
import com.nbicc.dp.modular.exception.custom.CustomExceptionEnum;
import com.nbicc.dp.wsgateway.common.WsPush;
import com.nbicc.dp.wsgateway.holder.PanelHolder;
import com.nbicc.dp.wsgateway.iservice.IWsPanelService;
import com.nbicc.dp.wsgateway.model.WsPanel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author: lilingyan
 */
@Slf4j
@Service("WsPanelService")
public class WsPanelService implements IWsPanelService{

    @Autowired
    private PanelHolder panelHolder;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PanelOnOffService panelOnOffService;

    @Override
    public Map<String , WsPanel> listAllOnlinePanel() {
        return panelHolder.getWsPanelMap();
    }

    @Override
    public Integer pushMsgToPanel(WsPush wsPush) {
        Integer pushCount = 0;
        List<WsPanel> wsPanelList = panelHolder.getWsPanelsThatContainsWsWidget(wsPush.getWidgetInstanceId());
        if(wsPanelList == null || wsPanelList.size() == 0){
            return pushCount;
        }
        for (WsPanel wsPanel : wsPanelList) {
            if(wsPanel.getSession().isOpen()){
                TextMessage wsPushTextMessage = null;
                //如果只是json转化出错 则跳过发送
                try {
                    wsPushTextMessage = new TextMessage(objectMapper.writeValueAsString(wsPush));
                } catch (JsonProcessingException e) {
                    log.error(ExceptionUtil.getStackTraceInfo(e));
                    continue;
                }
                //如果是发送出错  则关闭连接
                try {
                    wsPanel.getSession().sendMessage(wsPushTextMessage);
                    pushCount++;
                } catch (IOException e) {
                    log.error(ExceptionUtil.getStackTraceInfo(e));
                    if(wsPanel.getSession().isOpen()){
                        try {
                            wsPanel.getSession().close();
                        } catch (IOException e1) {
                            log.error(ExceptionUtil.getStackTraceInfo(e1));
                        }
                    }
                    panelOnOffService.offline(wsPanel.getSession());
                }
            }
        }
        return  0;
    }

}
